package com.dmcloud.zuul.filter.abstractzuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * 一个通用的抽象过滤器类
 * 模板设计
 * Created by xiaodao
 * date: 2019/10/26
 */
public abstract  class AbstractZuulFilter extends ZuulFilter {
    //用于在过滤器之间传递消息,数据保存在每一个请求的TreadLocal 中
    //扩展了currentHashMap
    RequestContext context;

    private final static String NEXT= "next";
    @Override
    public boolean shouldFilter() {
        RequestContext   ctx = RequestContext.getCurrentContext();
        return (boolean) ctx.getOrDefault("next",true);
    }

    @Override
    public Object run() throws ZuulException {
        context =  RequestContext.getCurrentContext();

        return cRun();
    }

    protected abstract Object cRun();

    /**
     * 如果访问失败了.就直接返回失败
     * @param code
     * @param message
     * @return
     */
   public Object fail(int code, String message){
        context.set(NEXT,false);
        context.setSendZuulResponse(false);
        context.getResponse().setContentType("text/html;charset=UTF-8");
        context.setResponseStatusCode(code);
        context.setResponseBody(String.format("{\"result\": \"%s\"}",message));
        return null;
    }

   public Object success(){
        context.set(NEXT,true);
        return  null;
    }
}
